<template>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="设备分组" prop="groupId">
        <el-tree-select
          v-model="queryParams.groupId"
          :data="dataList"
          :props="defaultProps"
          check-strictly
          node-key="id"
          placeholder="请选择设备分组"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-select
          v-model="queryParams.deviceType"
          placeholder="请选择设备类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MQTT_DEVICE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="水量上送" prop="isUpload">
        <el-select
          v-model="queryParams.isUpload"
          placeholder="请选择水量上送"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MQTT_DEVICE_ISTRUE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="设备在线" prop="isOnline">
        <el-select
          v-model="queryParams.isOnline"
          placeholder="请选择设备在线"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.IOT_DEVICE_STATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="设备地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入设备地址"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['mqtt:device:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['mqtt:device:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleBatchQRCodePreview"
          :loading="batchPreviewLoading"
        >
          <Icon icon="ep:view" class="mr-5px" /> 批量二维码预览
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button plain @click="handleSyncDevice" :loading="batchPreviewLoading">
          <Icon icon="ep:view" class="mr-5px" /> 设备同步
        </el-button>

        <el-button type="primary" plain @click="handleSyncWater" :loading="batchPreviewLoading">
          <Icon icon="ep:view" class="mr-5px" /> 水量更新
        </el-button>

        <el-button type="danger" plain @click="handleSendFlow" :loading="batchPreviewLoading">
          <Icon icon="ep:view" class="mr-5px" /> 水量一键上送
        </el-button>

        <!-- <el-button plain @click="handleSyncSun" :loading="batchPreviewLoading">
          <Icon icon="ep:view" class="mr-5px" /> 水质更新
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <el-row :gutter="24">
    <!-- 筛选栏 -->
    <!-- <el-col :span="4">
      <ContentWrap style="height: 98%">
        <DeviceTree @node-click="handleNodeClick" />
      </ContentWrap>
    </el-col> -->
    <!-- 表格数据 -->
    <el-col :span="24">
      <ContentWrap>
        <el-table
          v-loading="loading"
          :data="list"
          :stripe="true"
          border
          :show-overflow-tooltip="true"
          height="calc(100vh - 320px)"
        >
          <el-table-column type="selection" label="编号" prop="id" fixed="left" width="80" />
          <el-table-column label="设备类型" align="left" prop="deviceType" width="100" fixed="left">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.MQTT_DEVICE_TYPE" :value="scope.row.deviceType" />
            </template>
          </el-table-column>
          <el-table-column label="设备名称" prop="deviceName" width="300" fixed="left" />
          <el-table-column label="上送名称" prop="countryName" width="160" fixed="left" />

          <el-table-column label="状态" align="center" prop="state">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.IOT_DEVICE_STATE" :value="scope.row.isOnline" />
            </template>
          </el-table-column>
          <el-table-column label="水量上送" align="center" prop="isUpload" width="100">
            <template #default="scope">
              <div @click="handleUploadClick(scope.row.id)" style="cursor: pointer">
                <dict-tag :type="DICT_TYPE.MQTT_DEVICE_ISTRUE" :value="scope.row.isUpload" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="网关编号" align="left" prop="gatewayId" width="120" />
          <el-table-column label="设备地址" align="left" prop="address" width="260" />

          <!-- <el-table-column label="设备图片" align="center" prop="picUrl" width="100">
            <template #default="scope">
              <el-image
                :src="uploadUrl + scope.row.picUrl || defaultImage"
                fit="cover"
                class="device-image"
              />
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="物联网卡号(ICCID)" align="left" prop="firmwareId" width="190" /> -->
          <el-table-column label="设备唯一码" align="left" prop="deviceKey" width="120" />
          <!-- <el-table-column label="设备编号" align="left" prop="serialNumber" width="120" /> -->
          <el-table-column label="报警状态" align="left" prop="alarmStatus" width="90">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.MQTT_CONFIG_ENABLED" :value="scope.row.alarmStatus" />
            </template>
          </el-table-column>
          <el-table-column label="报警设置" align="left" prop="alarmDefult" width="110">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.MQtt_DEVICE_DEFULT_ALERM" :value="scope.row.alarmDefult" />
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="left"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />

          <el-table-column label="操作" align="left" min-width="300" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="success"
                @click="uploadJCJ(scope.row)"
                v-hasPermi="['mqtt:device:update']"
              >
                流量上报
              </el-button>

              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['mqtt:device:update']"
              >
                编辑
              </el-button>

              <!--  <el-button link type="success" @click="openGatewayDriverDialog(scope.row)">
                驱动、网关
              </el-button>
              <el-button link type="primary" @click="openHistoryReportDialog(scope.row)">
                历史
              </el-button> -->
              <!-- <el-button link type="warning" @click="openAuth(scope.row)"> 授权 </el-button> -->
              <el-button
                link
                type="success"
                @click="openEditDetail(scope.row)"
                v-hasPermi="['mqtt:device:update']"
              >
                详情
              </el-button>

              <el-button link type="info" @click="openQRCodeDialog(scope.row)"> 二维码 </el-button>

              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['mqtt:device:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
      <DeviceForm ref="formRef" @success="getList" />

      <EditDettail ref="editDetailRef" @success="getList" />

      <QRCodeDialog ref="qrcodeDialogRef" />
      <BatchQRCodeDialog ref="batchQRCodeDialogRef" />
    </el-col>
  </el-row>
  <GatewayDriverDialog v-model:visible="gatewayDriverDialogVisible" :row="currentRow" />
  <DevicereportDialog v-model:visible="historyReportDialogVisible" :row="historyReportRow" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DeviceApi, DeviceVO } from '@/api/mqtt/device'
import DeviceForm from './DeviceForm.vue'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
// import DeviceTree from './DeviceTree.vue'
import GatewayDriverDialog from './GatewayDriverDialog.vue'
import { DeviceGroupApi } from '@/api/mqtt/devicegroup'
import DevicereportDialog from '../devicereport/index.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import EditDettail from './EditDetail.vue'
import QRCodeDialog from './QRCodeDialog.vue'
import BatchQRCodeDialog from './BatchQRCodeDialog.vue'
import { ElMessageBox } from 'element-plus'

import { useRouter } from 'vue-router'

const router = useRouter()

const gatewayDriverDialogVisible = ref(false)
const currentRow = ref<any>(null)
const historyReportDialogVisible = ref(false)
const historyReportRow = ref<any>(null)

/** IoT 设备 列表 */
defineOptions({ name: 'Device' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const uploadUrl = import.meta.env.VITE_BASE_URL + '/cert/'
const defaultImage = '/0.jpg'
const loading = ref(true) // 列表的加载中
const list = ref<DeviceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  groupId: undefined,
  deviceStatus: undefined,
  deviceKey: undefined,
  deviceName: undefined,
  isUpload: undefined,
  deviceType: undefined,
  gatewayId: undefined,
  isOnline: undefined,
  areaId: undefined,
  address: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const batchPreviewLoading = ref(false) // 批量预览的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeviceApi.getDevicePermissionPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if (type === 'update' && id) {
    const row = list.value.find((item) => item.id === id)
    formRef.value.open(type, id, {
      address: row?.address,
      longitude: row?.longitude,
      latitude: row?.latitude
    })
  } else {
    formRef.value.open(type, id)
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeviceApi.deleteDevice(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
//更新 是否需要上送
const handleUploadClick = async (id: number) => {
  try {
    // 发起删除
    await DeviceApi.updateDeviceIsUpload(id)
    message.success('更新成')
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DeviceApi.exportDevice(queryParams)
    download.excel(data, 'IoT 设备.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleSyncDevice = async () => {
  const data = await DeviceApi.lisUpdateDevice()
  message.alertSuccess(data.msg)
}

const handleSyncWater = async () => {
  const data = await DeviceApi.lisWater()
  message.alertSuccess(data)
}
const handleSendFlow = async () => {
  const data = await DeviceApi.updateHourAndSend()
  message.alertSuccess(data)
}

const uploadJCJ = async (row: any) => {
  if (row.isUpload == '0') {
    message.alertError('该条记录不能上送！开启记录上送')
    return
  }
  const data = await DeviceApi.uploadJCJ(row.gatewayId)
  if (data == 0) {
    message.alertSuccess('上送成功')
  } else {
    message.alertError(data.status)
  }
}
const handleSyncSun = async () => {
  const data = await DeviceApi.getListMin10()
  message.alertSuccess(data.msg)
}

/** 批量二维码预览操作 */
const handleBatchQRCodePreview = async () => {
  try {
    // 确认操作
    await ElMessageBox.confirm(
      '确定要预览所有设备的二维码吗？这将为当前页面的所有设备生成二维码预览。',
      '批量二维码预览',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    batchPreviewLoading.value = true

    // 获取当前页面的所有设备
    const devices = list.value
    if (devices.length === 0) {
      message.warning('当前没有设备数据')
      return
    }

    // 打开批量二维码预览对话框
    batchQRCodeDialogRef.value.open(devices)
  } catch (error: any) {
    if (error !== 'cancel') {
      message.error('批量二维码预览失败')
      console.error('批量二维码预览失败:', error)
    }
  } finally {
    batchPreviewLoading.value = false
  }
}

/** 处理左侧筛选栏点击 */
const handleNodeClick = (node: any) => {
  queryParams.groupId = node.id === 0 ? undefined : node.id
  getList()
}

/** 打开网关/驱动对话框 */
const openGatewayDriverDialog = (row: any) => {
  currentRow.value = row
  gatewayDriverDialogVisible.value = true
}

/** 打开历史报表对话框 */
const openHistoryReportDialog = (row: any) => {
  historyReportRow.value = row
  historyReportDialogVisible.value = true
}
const dataList = ref<Tree[]>([]) // 树形结构
/** 初始化 **/
onMounted(async () => {
  // 获取设备分组信息
  const res = await DeviceGroupApi.getSimpleGroupList(null)
  dataList.value = []
  dataList.value.push(...handleTree(res))
  getList()
})

const editDetailRef = ref()
const openEditDetail = async (row: any) => {
  editDetailRef.value.open(row)
  // // 使用 router.push 跳转到目标页面，并传递数据
  // router.push({
  //   name: 'DeviceInfo', // 目标路由的名称
  //   params: { id: row.id }, // 通过 params 传递 ID
  //   query: { data: JSON.stringify(row) } // 通过 query 传递整个对象
  // })
}

const qrcodeDialogRef = ref()
const openQRCodeDialog = async (row: any) => {
  qrcodeDialogRef.value.open(row)
}

const batchQRCodeDialogRef = ref()

const openAuth = async (row: any) => {}

// 设备表格引用
const deviceTableRef = ref()

// 获取选中的设备
const getSelectedDevices = () => {
  return deviceTableRef.value?.getSelectionRows() || []
}

// 定义 expose 方法
defineExpose({ getSelectedDevices, resetQuery })
</script>

<style scoped>
/* 图片样式限制，避免原始图片过大导致预览异常 */
.device-image {
  width: 40px; /* 固定表格中图片的宽高 */
  height: 40px;
  object-fit: cover; /* 保持图片比例，避免拉伸 */
}
</style>
